<template>
  <div class="hello-app">
    <h1>{{ message }}</h1>
    <button @click="changeMessage">Click Me!</button>
    <p>当前时间: {{ currentTime }}</p>
    <div class="info">
      <p>这是Hello World测试应用</p>
    </div>

    <!-- 签名测试区域 -->
    <div class="signature-test">
      <h2>抖音签名测试</h2>
      <div class="test-input">
        <label>房间号:</label>
        <input v-model="roomNum" placeholder="请输入房间号或直播间链接" />
        <button @click="testSignature" :disabled="loading">
          {{ loading ? '获取中...' : '获取签名' }}
        </button>
      </div>

      <!-- 测试结果显示 -->
      <div class="results" v-if="results.step > 0">
        <h3>测试结果:</h3>
        
        <!-- 步骤1: 直播间信息 -->
        <div class="result-item" v-if="results.step >= 1">
          <h4>1. 直播间信息:</h4>
          <div class="result-content">
            <p><strong>房间ID:</strong> {{ results.liveInfo?.roomId || '获取失败' }}</p>
            <p><strong>用户ID:</strong> {{ results.liveInfo?.uniqueId || '获取失败' }}</p>
            <p><strong>直播状态:</strong> {{ results.liveInfo?.status || '未知' }}</p>
            <p><strong>主播昵称:</strong> {{ results.liveInfo?.nickname || '未知' }}</p>
          </div>
        </div>

        <!-- 步骤2: IM连接信息 -->
        <div class="result-item" v-if="results.step >= 2">
          <h4>2. IM连接信息:</h4>
          <div class="result-content">
            <p><strong>Cursor:</strong> {{ results.imInfo?.cursor || '获取失败' }}</p>
            <p><strong>InternalExt:</strong> {{ results.imInfo?.internalExt ? '已获取' : '获取失败' }}</p>
            <p><strong>推送服务器:</strong> {{ results.imInfo?.pushServer || '未知' }}</p>
          </div>
        </div>

        <!-- 步骤3: msToken -->
        <div class="result-item" v-if="results.step >= 3">
          <h4>3. msToken:</h4>
          <div class="result-content">
            <p><strong>msToken:</strong> {{ results.msToken ? '已生成' : '生成失败' }}</p>
            <p><strong>长度:</strong> {{ results.msToken?.length || 0 }}</p>
          </div>
        </div>

        <!-- 步骤4: 签名生成 -->
        <div class="result-item" v-if="results.step >= 4">
          <h4>4. 签名生成:</h4>
          <div class="result-content">
            <p><strong>X-Bogus签名:</strong> {{ results.signature || '生成失败' }}</p>
            <p><strong>签名状态:</strong> {{ results.signature ? '✅ 成功' : '❌ 失败' }}</p>
          </div>
        </div>
      </div>

      <!-- 多房间连接测试 -->
      <div class="multi-connection-test" v-if="results.signature">
        <h3>🔗 多房间连接测试</h3>
        <div class="test-description">
          <p><strong>测试目的:</strong> 验证同一个签名是否能同时连接多个房间</p>
          <p><strong>当前签名来源:</strong> 房间 {{ results.liveInfo?.roomId }}</p>
        </div>
        
        <div class="room-connections">
          <div class="connection-card" v-for="room in testRooms" :key="room.roomId">
            <h4>{{ room.name }}</h4>
            <div class="room-info">
              <p><strong>房间ID:</strong> {{ room.roomId }}</p>
              <p><strong>使用签名:</strong> {{ room.useCurrentSignature ? '当前签名' : '专用签名' }}</p>
            </div>
            
            <div class="connection-controls">
              <button 
                @click="connectToRoom(room)" 
                :disabled="room.connecting || loading"
                class="connect-btn"
                :class="{ 'connected': room.connected, 'connecting': room.connecting }"
              >
                {{ getConnectButtonText(room) }}
              </button>
              
              <button 
                @click="disconnectFromRoom(room)" 
                :disabled="!room.connected"
                class="disconnect-btn"
              >
                断开连接
              </button>
            </div>
            
            <div class="connection-status">
              <div class="status-indicator" :class="getStatusClass(room)"></div>
              <span class="status-text">{{ getStatusText(room) }}</span>
            </div>
            
            <div class="connection-details" v-if="room.connected || room.error">
              <p v-if="room.connectedTime"><strong>连接时间:</strong> {{ room.connectedTime }}</p>
              <p v-if="room.duration"><strong>持续时间:</strong> {{ room.duration }}s</p>
              <p v-if="room.error" class="error-text"><strong>错误:</strong> {{ room.error }}</p>
              <p v-if="room.messageCount"><strong>接收消息:</strong> {{ room.messageCount }} 条</p>
            </div>
          </div>
        </div>
        
        <!-- 测试结果统计 -->
        <div class="test-results" v-if="hasConnectionAttempts">
          <h4>📊 测试结果统计</h4>
          <div class="stats-grid">
            <div class="stat-item">
              <span class="stat-label">总连接数:</span>
              <span class="stat-value">{{ totalConnections }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">成功连接:</span>
              <span class="stat-value success">{{ successfulConnections }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">失败连接:</span>
              <span class="stat-value error">{{ failedConnections }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">当前活跃:</span>
              <span class="stat-value active">{{ activeConnections }}</span>
            </div>
          </div>
          
          <div class="test-conclusion">
            <p><strong>结论:</strong> 
              <span v-if="successfulConnections > 1" class="conclusion success">
                ✅ 同一个签名可以同时连接多个房间
              </span>
              <span v-else-if="successfulConnections === 1 && totalConnections > 1" class="conclusion partial">
                ⚠️ 签名只能连接一个房间，其他连接失败
              </span>
              <span v-else-if="totalConnections > 0" class="conclusion failed">
                ❌ 所有连接都失败了
              </span>
            </p>
          </div>
        </div>
      </div>

      <!-- 错误信息 -->
      <div class="error" v-if="error">
        <h4>错误信息:</h4>
        <p>{{ error }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { getSignature, getMsToken } from '@/core/signature.js'
import { getLiveInfo, getImInfo } from '@/core/request'
import { DyCast } from '@/core/dycast'

const message = ref('Hello World!')
const currentTime = ref('')

// 签名测试相关
const roomNum = ref('447584845941') // 正确房间号
const loading = ref(false)
const error = ref('')

// 测试结果
const results = ref({
  step: 0,
  liveInfo: null as any,
  imInfo: null as any,
  msToken: '',
  signature: ''
})
// 多房间连接测试相关
interface TestRoom {
  roomId: string
  name: string
  useCurrentSignature: boolean
  connecting: boolean
  connected: boolean
  connectedTime?: string
  duration?: number
  error?: string
  messageCount?: number
  dycast?: any // 使用any类型避免类型冲突
  connectStartTime?: number
  durationTimer?: number
}

const testRooms = ref<TestRoom[]>([
  {
    roomId: '447584845941',
    name: '原房间',
    useCurrentSignature: true,
    connecting: false,
    connected: false
  },
  {
    roomId: '805255077831',
    name: '测试房间B',
    useCurrentSignature: true,
    connecting: false,
    connected: false
  },
  {
    roomId: '71238526711',
    name: '测试房间C',
    useCurrentSignature: true,
    connecting: false,
    connected: false
  }
])

// 计算属性
const hasConnectionAttempts = computed(() => {
  return testRooms.value.some(room => room.connected || room.error)
})

const totalConnections = computed(() => {
  return testRooms.value.filter(room => room.connected || room.error).length
})

const successfulConnections = computed(() => {
  return testRooms.value.filter(room => room.connected).length
})

const failedConnections = computed(() => {
  return testRooms.value.filter(room => room.error && !room.connected).length
})

const activeConnections = computed(() => {
  return testRooms.value.filter(room => room.connected).length
})

const changeMessage = () => {
  message.value = message.value === 'Hello World!' ? 'Hello Vue 3!' : 'Hello World!'
}

const updateTime = () => {
  currentTime.value = new Date().toLocaleString()
}

// 测试签名获取流程
const testSignature = async () => {
  if (!roomNum.value.trim()) {
    error.value = '请输入房间号'
    return
  }

  loading.value = true
  error.value = ''
  results.value = { step: 0, liveInfo: null, imInfo: null, msToken: '', signature: '' }

  try {
    // 步骤1: 获取直播间信息
    console.log('步骤1: 获取直播间信息...')
    const liveInfo = await getLiveInfo(roomNum.value.trim())
    results.value.liveInfo = liveInfo
    results.value.step = 1
    console.log('直播间信息:', liveInfo)

    if (!liveInfo.roomId || !liveInfo.uniqueId) {
      throw new Error('无法获取房间ID或用户ID')
    }

    // 步骤2: 获取IM连接信息
    console.log('步骤2: 获取IM连接信息...')
    const imInfo = await getImInfo(liveInfo.roomId, liveInfo.uniqueId)
    results.value.imInfo = imInfo
    results.value.step = 2
    console.log('IM信息:', imInfo)

    // 步骤3: 生成msToken
    console.log('步骤3: 生成msToken...')
    const msToken = getMsToken(184)
    results.value.msToken = msToken
    results.value.step = 3
    console.log('msToken:', msToken)

    // 步骤4: 生成签名
    console.log('步骤4: 生成签名...')
    
    // 检查mssdk是否可用
    if (typeof window !== 'undefined' && (window as any).byted_acrawler) {
      const signature = getSignature(liveInfo.roomId, liveInfo.uniqueId)
      results.value.signature = signature
      results.value.step = 4
      console.log('签名生成成功:', signature)
    } else {
      throw new Error('mssdk.js 未加载或 byted_acrawler 不可用')
    }

  } catch (err: any) {
    console.error('签名获取失败:', err)
    error.value = err.message || '未知错误'
  } finally {
    loading.value = false
  }
}

// 多房间连接相关方法
const connectToRoom = async (room: TestRoom) => {
  if (room.connecting || room.connected) return
  
  room.connecting = true
  room.error = undefined
  room.connectStartTime = Date.now()
  
  try {
    console.log(`开始连接房间 ${room.roomId}...`)
    
    // 创建DyCast实例
    const dycast = new DyCast(room.roomId)
    room.dycast = dycast
    
    // 设置事件监听器
    dycast.on('open', () => {
      room.connected = true
      room.connecting = false
      room.connectedTime = new Date().toLocaleTimeString()
      room.messageCount = 0
      
      // 开始计时器
      room.durationTimer = window.setInterval(() => {
        if (room.connectStartTime) {
          room.duration = Math.floor((Date.now() - room.connectStartTime) / 1000)
        }
      }, 1000)
      
      console.log(`✅ 房间 ${room.roomId} 连接成功`)
    })
    
    dycast.on('close', (code: number, reason: string) => {
      console.log(`❌ 房间 ${room.roomId} 连接断开: ${reason} (${code})`)
      
      // 只有在非手动断开时才设置错误信息
      if (!room.error && code !== 1000) {
        room.error = `连接断开: ${reason} (${code})`
      }
      
      // 清理状态
      room.connected = false
      room.connecting = false
      
      if (room.durationTimer) {
        clearInterval(room.durationTimer)
        room.durationTimer = undefined
      }
    })
    
    dycast.on('error', (err: any) => {
      console.error(`❌ 房间 ${room.roomId} 连接错误:`, err)
      
      room.connected = false
      room.connecting = false
      room.error = err.message || '连接错误'
      
      if (room.durationTimer) {
        clearInterval(room.durationTimer)
        room.durationTimer = undefined
      }
    })
    
    // 监听消息
    dycast.on('chat', () => {
      if (room.messageCount !== undefined) {
        room.messageCount++
      }
    })
    
    dycast.on('gift', () => {
      if (room.messageCount !== undefined) {
        room.messageCount++
      }
    })
    
    dycast.on('like', () => {
      if (room.messageCount !== undefined) {
        room.messageCount++
      }
    })
    
    // 连接到房间
    await dycast.connect()
    
  } catch (err: any) {
    console.error(`❌ 房间 ${room.roomId} 连接失败:`, err)
    
    // 连接失败时清理状态
    room.connected = false
    room.connecting = false
    room.error = err.message || '连接失败'
    
    // 清理定时器
    if (room.durationTimer) {
      clearInterval(room.durationTimer)
      room.durationTimer = undefined
    }
    
    // 清理dycast实例
    if (room.dycast) {
      try {
        room.dycast.close(1006, '连接失败清理')
      } catch (closeErr) {
        console.error(`清理dycast实例失败:`, closeErr)
      }
      room.dycast = undefined
    }
  }
}

const disconnectFromRoom = (room: TestRoom) => {
  try {
    console.log(`开始断开房间 ${room.roomId} 连接`)
    
    // 先清理定时器
    if (room.durationTimer) {
      clearInterval(room.durationTimer)
      room.durationTimer = undefined
    }
    
    // 设置状态为断开中
    room.connecting = false
    
    if (room.dycast) {
      // 移除所有事件监听器，避免在断开过程中触发事件
      room.dycast.off('open')
      room.dycast.off('close')
      room.dycast.off('error')
      room.dycast.off('chat')
      room.dycast.off('gift')
      room.dycast.off('like')
      
      // 关闭连接
      room.dycast.close(1000, '手动断开连接')
      room.dycast = undefined
    }
    
    // 更新房间状态
    room.connected = false
    room.error = undefined
    room.connectedTime = undefined
    room.duration = undefined
    room.messageCount = undefined
    room.connectStartTime = undefined
    
    console.log(`✅ 房间 ${room.roomId} 连接已断开`)
  } catch (err: any) {
    console.error(`❌ 断开房间 ${room.roomId} 连接失败:`, err)
    
    // 即使断开失败，也要强制清理所有状态
    room.connected = false
    room.connecting = false
    room.dycast = undefined
    room.error = `断开连接时出错: ${err.message}`
    
    if (room.durationTimer) {
      clearInterval(room.durationTimer)
      room.durationTimer = undefined
    }
  }
}

// UI辅助方法
const getConnectButtonText = (room: TestRoom) => {
  if (room.connecting) return '连接中...'
  if (room.connected) return '已连接'
  return '连接'
}

const getStatusClass = (room: TestRoom) => {
  if (room.connecting) return 'connecting'
  if (room.connected) return 'connected'
  if (room.error) return 'error'
  return 'disconnected'
}

const getStatusText = (room: TestRoom) => {
  if (room.connecting) return '连接中...'
  if (room.connected) return '已连接'
  if (room.error) return '连接失败'
  return '未连接'
}

onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  
  // 检查mssdk是否已加载
  console.log('检查mssdk状态:', typeof (window as any)?.byted_acrawler)
})

onUnmounted(() => {
  // 清理所有连接
  testRooms.value.forEach(room => {
    disconnectFromRoom(room)
  })
})
</script>

<style scoped>
.hello-app {
  text-align: center;
  padding: 2rem;
  font-family: Arial, sans-serif;
}

h1 {
  color: #42b883;
  margin-bottom: 2rem;
}

button {
  background: #42b883;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  margin: 10px;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover {
  background: #369970;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.info {
  margin-top: 2rem;
  padding: 1rem;
  background: #f5f5f5;
  border-radius: 8px;
  display: inline-block;
}

.info p {
  margin: 0.5rem 0;
  color: #666;
}

/* 签名测试样式 */
.signature-test {
  margin-top: 3rem;
  padding: 2rem;
  background: #fff;
  border: 2px solid #42b883;
  border-radius: 12px;
  text-align: left;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.signature-test h2 {
  color: #42b883;
  text-align: center;
  margin-bottom: 2rem;
}

.test-input {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
}

.test-input label {
  font-weight: bold;
  color: #333;
}

.test-input input {
  flex: 1;
  min-width: 300px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.results {
  margin-top: 2rem;
}

.result-item {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #42b883;
}

.result-item h4 {
  margin: 0 0 1rem 0;
  color: #42b883;
}

.result-content p {
  margin: 0.5rem 0;
  word-break: break-all;
}

.result-content strong {
  color: #333;
}

/* 多房间连接测试样式 */
.multi-connection-test {
  margin-top: 2rem;
  padding: 1.5rem;
  background: #f0f9ff;
  border: 2px solid #0ea5e9;
  border-radius: 8px;
}

.multi-connection-test h3 {
  color: #0ea5e9;
  margin-bottom: 1rem;
  text-align: center;
}

.test-description {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: white;
  border-radius: 6px;
  border-left: 4px solid #0ea5e9;
}

.test-description p {
  margin: 0.3rem 0;
  color: #374151;
}

.room-connections {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.connection-card {
  background: white;
  padding: 1.2rem;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.connection-card h4 {
  margin: 0 0 1rem 0;
  color: #1f2937;
  font-size: 1.1rem;
}

.room-info {
  margin-bottom: 1rem;
}

.room-info p {
  margin: 0.3rem 0;
  font-size: 0.9rem;
  color: #6b7280;
}

.connection-controls {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.connect-btn, .disconnect-btn {
  flex: 1;
  padding: 8px 12px !important;
  margin: 0 !important;
  font-size: 0.9rem !important;
}

.connect-btn.connecting {
  background: #f59e0b !important;
}

.connect-btn.connected {
  background: #059669 !important;
}

.disconnect-btn {
  background: #dc2626 !important;
}

.disconnect-btn:hover {
  background: #b91c1c !important;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #9ca3af;
}

.status-indicator.connecting {
  background: #f59e0b;
  animation: pulse 1.5s infinite;
}

.status-indicator.connected {
  background: #059669;
}

.status-indicator.error {
  background: #dc2626;
}

.status-text {
  font-size: 0.9rem;
  color: #374151;
  font-weight: 500;
}

.connection-details {
  padding: 0.8rem;
  background: #f9fafb;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
}

.connection-details p {
  margin: 0.3rem 0;
  font-size: 0.85rem;
  color: #6b7280;
}

.error-text {
  color: #dc2626 !important;
}
.test-results {
  background: white;
  padding: 1.2rem;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.test-results h4 {
  margin: 0 0 1rem 0;
  color: #1f2937;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.8rem;
  background: #f9fafb;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.stat-label {
  font-size: 0.9rem;
  color: #6b7280;
}

.stat-value {
  font-weight: bold;
  font-size: 1.1rem;
}

.stat-value.success {
  color: #059669;
}

.stat-value.error {
  color: #dc2626;
}

.stat-value.active {
  color: #0ea5e9;
}

.test-conclusion {
  padding: 1rem;
  background: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #0ea5e9;
}

.test-conclusion p {
  margin: 0;
  font-weight: bold;
  color: #1f2937;
}

.conclusion {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: bold;
}

.conclusion.success {
  background: #ecfdf5;
  color: #059669;
}

.conclusion.partial {
  background: #fef3c7;
  color: #d97706;
}

.conclusion.failed {
  background: #fef2f2;
  color: #dc2626;
}

.error {
  margin-top: 2rem;
  padding: 1rem;
  background: #fff5f5;
  border: 1px solid #fed7d7;
  border-radius: 8px;
  color: #c53030;
}

.error h4 {
  margin: 0 0 0.5rem 0;
  color: #c53030;
}

/* 动画效果 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 响应式布局 */
@media (max-width: 768px) {
  .signature-test {
    padding: 1rem;
    margin: 1rem;
  }
  
  .room-connections {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .connection-controls {
    flex-direction: column;
  }
}
</style>